const util = require('../../../../utils/util.js')
const app = getApp()

// 实例化API核心类
const qqmapsdk = app.globalData.qqmapsdk

Page({

  /**
   * 页面的初始数据
   */
  data: {
    markers: '',
    poi: {
      latitude: '',
      longitude: ''
    },
    addressName: '',
    time: '',
    timer: '',
    timer2: '', // 用来每个一段时间自动刷新一次定位

    lessonid: '',
    stuLocation: '',
    teaLocation: '',
    distance_value: ''
  },

  getAddress(e) {
    var that = this;
    qqmapsdk.reverseGeocoder({
      success: function (res) {
        // console.log(res);
        that.setData({
          addressName: res.result.address
        })
        var res = res.result;
        var mks = [];
        //当get_poi为0时或者为不填默认值时，检索目标位置，按需使用
        mks.push({ // 获取返回结果，放到mks数组中
          title: res.address,
          id: 0,
          latitude: res.location.lat,
          longitude: res.location.lng,
          iconPath: '/images/map/myPosition.png', // 图标路径
          width: 21,
          height: 28,
          callout: { //在markers上展示地址名称，根据需求是否需要
            content: res.address,
            color: '#000',
            display: 'ALWAYS'
          }
        });
        that.setData({ // 设置markers属性和地图位置poi，将结果在地图展示
          markers: mks,
          poi: {
            latitude: res.location.lat,
            longitude: res.location.lng
          },
          stuLocation: res.location.lat + "," + res.location.lng
        });
        console.log(that.data.stuLocation)
        that.teaLocation()
      },
      fail: function (error) {
        console.error(error);
      },
      complete: function (res) {
        console.log(res);
      }
    })
  },
  getTime: function () {
    let that = this
    let time = that.data.time
    that.setData({
      timer: setInterval(function () {
        time = util.formatTime(new Date())
        that.setData({
          time: time.substr(-8)
        });
        if (time == 0) {
          // 页面跳转后，要把定时器清空掉，免得浪费性能
          clearInterval(that.data.timer)
        }
      }, 1000)
    })
  },

  rePosition: function () {
    console.log('用户点了重新定位')
    this.getAddress()
  },

  checkIn: function () {
    console.log('用户点击了签到')

    var that = this
    var nowTime = util.formatTime(new Date())

    wx.showModal({
      title: '请确认打卡信息',
      // content: '请确认待整改项已整改完毕！',
      content: `地点：${this.data.addressName}\n时间：${nowTime}\n距离：${this.data.distance_value}米`, // 开发者工具上没有换行，真机调试时会有的
      confirmText: '确认',
      success(res) {
        if (res.confirm) {
          console.log('用户点击确定')
          // 调起签到接口
          that.stuMap()

        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },

  stuMap: function (e) {
    var that = this;
    var userid = wx.getStorageSync('openid');
    console.log('userid：' + userid)
    console.log('lessonid：' + this.data.lessonid)
    console.log('stuLocation：' + that.data.stuLocation)

    wx.request({
      url: app.globalData.ServerUrl + 'map/checkLessonMapKey.php',
      data: {
        lessonid: that.data.lessonid,
      },
      method: 'POST',
      header: {
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      success: function (res) {
        console.log(res.data)
        if (res.data.teaLocation != undefined) {
          if (res.data.state != 'false') {
            if (that.data.distance_value <= '100000') {

              wx.request({
                url: app.globalData.ServerUrl + 'map/stuMapSign.php',
                data: {
                  userid: userid,
                  lessonid: that.data.lessonid,
                  stuAddress: that.data.addressName,
                  stuLocation: that.data.stuLocation,
                  distance_value: that.data.distance_value
                },
                method: 'POST',
                header: {
                  'Content-Type': 'application/x-www-form-urlencoded'
                },
                success: function (res) {
                  console.log(res.data)
                  if (res.data) {
                    wx.showToast({
                      title: '考勤成功',
                      icon: 'none'
                    })
                  } else {
                    wx.showToast({
                      title: '考勤失败',
                      icon: 'none'
                    })
                  }
                },
                fail: function (res) {},
                complete: function (res) {},
              })
            } else {
              wx.showToast({
                title: '当前距离过远！',
                icon: 'none'
              })
            }
          } else {
            wx.showToast({
              title: '签到已经结束!',
              icon: 'none'
            })
          }
        } else {
          wx.showToast({
            title: '该课程没有发起签到!',
            icon: 'none'
          })
        }
      },
      fail: function (res) {},
      complete: function (res) {},
    })
  },

  distance: function (e) {
    var _this = this;
    console.log('stu:' + _this.data.stuLocation, 'tea:' + _this.data.teaLocation)
    //调用距离计算接口
    qqmapsdk.calculateDistance({
      //mode: 'driving',//可选值：'driving'（驾车）、'walking'（步行），不填默认：'walking',可不填
      //from参数不填默认当前地址
      //获取表单提交的经纬度并设置from和to参数（示例为string格式）
      // from: e.detail.value.start || '', //若起点有数据则采用起点坐标，若为空默认当前地址
      // to: e.detail.value.dest, //终点坐标

      from: _this.data.stuLocation,
      to: _this.data.teaLocation,
      success: function (res) { //成功后的回调
        console.log(res);
        console.log('两点间的距离为：' + res.result.elements[0].distance) //距离
        _this.setData({
          distance_value: res.result.elements[0].distance
        })
        console.log('距离差值为：' + _this.data.distance_value)
        var res = res.result;
        var dis = [];
        for (var i = 0; i < res.elements.length; i++) {
          dis.push(res.elements[i].distance); //将返回数据存入dis数组，
        }
        _this.setData({ //设置并更新distance数据
          distance: dis
        });
      },
      fail: function (error) {
        console.error(error);
      },
      complete: function (res) {
        // console.log(res);
      }
    });
  },



  teaLocation: function (e) {
    var that = this;

    console.log(that.data.lessonid)
    wx.request({
      url: app.globalData.ServerUrl + 'map/getTeaLocation.php',
      data: {
        lessonid: that.data.lessonid,
      },
      method: 'POST',
      header: {
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      success: function (res) {
        console.log(res)
        if (!res.data == '') {
          that.setData({
            teaLocation: res.data.teaLocation
          })
          console.log(that.data.teaLocation)
          that.distance()
        } else {
          wx.showToast({
            title: '教师还未发起签到哟',
            icon: 'none'
          })
        }

      },
    })
  },


  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this
    that.setData({
        timer2: setInterval(function () {
          that.getAddress()
        }, 200000), // 每20秒刷新一次定位
        lessonid: options.lessonid
      }),
      that.getTime()
    that.getAddress()


  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    clearInterval(this.data.timer)
    clearInterval(this.data.timer2)
    console.log("定时器已被清除")
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})